<template>
  <div
    v-loading.fullscreen.lock="fullscreenLoading"
    v-if="shippingWay && loaded"
  >
    <el-popover placement="left" trigger="hover">
      <template>
        <el-divider content-position="left">常规操作</el-divider>
        <el-row :gutter="10" style="width: 800px">
          <el-col :span="12" class="menu-list">
            <div @click="toHdEdit" v-if="permission('to_hd_edit')">
              末端全编辑
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="toWaybillMergeSysRemark"
              v-if="permission('to_waybill_merge_remark')"
            >
              合单备注
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="toallocationtrace"
              v-if="permission('to_allocation_trace')"
            >
              分配轨迹
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="toHdEditOne('fileList')"
              v-if="permission('file_list')"
            >
              文件列表
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="toHdEditOne('receivable')"
              v-if="permission('receivable')"
            >
              应收应付
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="postEdit('waybillMergeTrackBack', '打回轨迹')"
              v-if="
                permission('waybill_merge_track_back') &&
                  this.data['status'] > 60 &&
                  this.data['status'] < 888
              "
            >
              打回轨迹
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="tobatchmergetrack"
              v-if="permission('to_batch_mergetrack')"
            >
              批量打回轨迹
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="postEdit('pushWaybillMergeToAgent', '推送至代理')"
              :disabled="disabled"
              v-if="permission('push_waybill_merge_to_agent')"
            >
              推送至代理({{ gentMap[data["customsClearanceAgent"]] }})
            </div>
          </el-col>

          <el-col :span="12" class="menu-list">
            <div
              @click="postEdit('pushWaybillMergeToAgent', '推送至代理')"
              :disabled="disabled"
              v-if="permission('push_waybill_merge_to_agent')"
            >
              推送至派送服务商({{ gentMap[data["afterSendServicer"]] }})
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="exportWaybillBill()"
              v-if="permission('export_waybill_bill')"
            >
              导出账单
            </div>
          </el-col>
          <el-col :span="12" class="menu-list">
            <div
              @click="
                postEdit('updatePortOfDestinationBillStatus', '生成目的港账单')
              "
              v-if="
                permission('update_port_bill_status') &&
                  this.data['portOfDestinationBillStatus'] == 0
              "
            >
              生成目的港账单
            </div>
          </el-col>
          <div v-if="excelInfoShow">
            <el-col
              :span="6"
              v-for="(item, k) in excelFileInfos"
              :key="k"
              class="menu-list"
            >
              <div @click="exportSingleTicket(item.id, item.fileName)">
                导出{{ item.fileName }}
              </div>
            </el-col>
          </div>
        </el-row>
      </template>
      <div slot="reference">
        <span class="text-blue">更多</span>
      </div>
    </el-popover>
  </div>
</template>

<script>
import { ajax, actionPermission } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { m } from "@/store/yg/common/local";

export default {
  data() {
    return {
      disabled: true,
      agentMap: {},
      fullscreenLoading: false,
      excelFileInfos: [],
      excelInfoShow: false,
      shippingWay: "",
      loaded: false,
      rules: {}
    };
  },
  props: ["row", "data", "more"],
  computed: {},
  mounted() {
    this.intitExcelFileInfos(0);
    this.fetchAgentApi();
    if (this.data["customsClearanceAgent"] && this.data["hasBeenPushed"] == 0) {
      this.disabled = true;
    }
    if (this.data["afterSendServicer"] && this.data["hasBeenPushed"] == 0) {
      this.disabled = true;
    }
    this.displayRules();
  },
  methods: {
    displayRules() {
      this.rules = {};
      this.loaded = false;
      var uri = "/waybill/extremeseafreight/list";

      if (this.shippingWay == "AIR" || this.shippingWay == "ZX") {
        uri = "/waybill/extremeairfreight/list";
      } else if (this.shippingWay == "LCL" || this.shippingWay == "FCL") {
        var uri = "/waybill/extremeseafreight/list";
      }

      if (
        !this.$store.state.main.entry ||
        this.$store.state.main.entry.uri != uri
      ) {
        let mainUri = "/api/entry/main?uri=" + uri;
        axios
          .post(constant.API_SERVER + mainUri)
          .then(response => {
            response.data.table.action.forEach(element => {
              if (element.displayRule) {
                this.rules[element.client.commit] = element.displayRule;
              }
            });
            this.loaded = true;
          })
          .catch(error => {});
      } else {
        for (var i in this.$store.state.main.entry.table.action) {
          let a = this.$store.state.main.entry.table.action[i];
          if (a.displayRule) {
            this.rules[a.client.commit] = a.displayRule;
          }
        }
        this.loaded = true;
      }
    },
    exportSingleTicket(excelFileId, fileName) {
      var param = {};
      param["statementTemplateId"] = excelFileId;
      // param["shippingWay"] = this.data['shippingWay'];
      param["waybillId"] = this.data["id"];
      param["code"] = "H";
      // console.info('excelFileId',param);
      ajax("reportWaybillData", param).then(
        res => {
          console.log(res);
          if (res.code == 200) {
            var path = (path = constant.FILE_SERVER + res.message);
            if (res.message) {
              fileName = res.message.substring(
                res.message.lastIndexOf("/") + 1,
                res.message.length
              );
            }
            location.href =
              constant.API_SERVER +
              "/open/downloadFileByHttp?fileName=" +
              fileName +
              "&path=" +
              path;
          } else {
            if (null != res.message) {
              this.$message.error("导出失败原因：" + res.message);
            } else {
              this.$message.error("导出失败");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    // 初始化 下载
    fetchAgentApi() {
      var param = {};
      var key = "agent_api_init";
      var agents = JSON.parse(sessionStorage.getItem(key));

      if (!agents || agents == "{}" || agents == null || agents == "null") {
        ajax("fetchAgentApi", param).then(
          res => {
            if (res.code == 200) {
              this.agentMap = res.data;
              sessionStorage.setItem(key, JSON.stringify(this.agentMap));
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.agentMap = agents;
      }
    },

    // 初始化 下载
    intitExcelFileInfos(loadType) {
      var param = {};
      this.shippingWay = this.data["shippingWay"];
      var key = "excel_init_H" + this.shippingWay;
      var fileInfos = JSON.parse(sessionStorage.getItem(key));
      if (
        loadType == 1 ||
        !fileInfos ||
        fileInfos == "{}" ||
        null == fileInfos ||
        "null" == fileInfos
      ) {
        param["code"] = "H";
        param["shippingWayType"] = this.shippingWay;
        ajax("intitExcelFileInfos", param).then(
          res => {
            this.excelInfoShow = true;
            if (res.code == 200) {
              this.excelFileInfos = res.data;
              sessionStorage.setItem(key, JSON.stringify(this.excelFileInfos));
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.excelFileInfos = fileInfos;
        this.excelInfoShow = true;
      }
    },
    permission(commit) {
      return actionPermission(this.rules, commit, this.data, this.$store.state);
      return true;
    },
    //合单备注
    toWaybillMergeSysRemark() {
      const url = "#/blank/waybill__mergewaybillremark__main";
      // this.$nextTick(()=>{
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    toHdEditOne(activeName) {
      //获取当前路由地址
      const urlPath = this.$route.path;
      console.info("urlPath:", urlPath);
      if (urlPath.indexOf("waybill__extremeseafreight__list") >= 0) {
        //console.info('这是海运');
        var url = "#/blank/waybill__seafreightHD__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url =
          url +
          "?shippingway=0&waybillId=" +
          this.data["id"] +
          "&activeName=" +
          activeName;
        window.open(url, "_blank");
      } else if (urlPath.indexOf("waybill__extremeairfreight__list") >= 0) {
        //console.info('这是空运');
        var url = "#/blank/waybill__airfreightHD__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url =
          url +
          "?shippingway=1&waybillId=" +
          this.data["id"] +
          "&activeName=" +
          activeName;
        window.open(url, "_blank");
      }
    },

    //分配轨迹
    toallocationtrace() {
      const url = "#/blank/waybill__allocationtrace__main";
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    //批量打回轨迹
    tobatchmergetrack() {
      const url = "#/blank/waybill__batchmergetrack__main";
      // this.$store.dispatch("loadBlankEntry", url);
      //location.href = url;
      window.open(url + "?waybillId=" + this.data["id"], "_blank");
      //this.$store.dispatch('loadBlankEntry', url);

      // })
    },

    toHdEdit() {
      //获取当前路由地址
      const urlPath = this.$route.path;
      console.info("urlPath:", urlPath);
      if (urlPath.indexOf("waybill__extremeseafreight__list") >= 0) {
        //console.info('这是海运');
        var url = "#/blank/waybill__seafreightHD__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url = url + "?shippingway=0&waybillId=" + this.data["id"];
        window.open(url, "_blank");
      } else if (urlPath.indexOf("waybill__extremeairfreight__list") >= 0) {
        //console.info('这是空运');
        var url = "#/blank/waybill__airfreightHD__main";
        // this.$store.dispatch("loadBlankEntry", url);
        url = url + "?shippingway=1&waybillId=" + this.data["id"];
        window.open(url, "_blank");
      }
    },
    postParamsEdit(postUrl, info, paramsName, params) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          param["status"] = this.data["status"];
          param[paramsName] = params;
          ajax(postUrl, param).then(
            res => {
              if (res.code != 200) {
                if (null != res.message) {
                  this.$message.error(m(res.message));
                } else {
                  this.$message.error("修改失败!");
                }
              } else {
                this.$message.success("修改成功!");
                this.centerDialogVisible = false;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    },
    exportWaybillBill() {
      this.fullscreenLoading = true;
      var param = {};
      param["id"] = this.data["id"];
      ajax("exportWaybillBill", param).then(
        res => {
          this.fullscreenLoading = false;
          if (null != res.message && res.message != "") {
            this.$message.error(m(res.message));
          } else {
            console.log(res);
            var path = constant.FILE_SERVER + res.path;
            location.href =
              constant.API_SERVER +
              "/open/downloadFileByHttp?fileName=" +
              res.fileName +
              "&path=" +
              path;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    //公共的后台请求
    postEdit(postUrl, info) {
      this.$confirm("此操作将" + info + ", 是否继续？")
        .then(_ => {
          this.fullscreenLoading = true;
          // TODO 保存操作
          var param = {};
          param["id"] = this.data["id"];
          param["status"] = this.data["status"];
          ajax(postUrl, param).then(
            res => {
              this.fullscreenLoading = false;
              if (res.code != 200) {
                console.log(res);
                if (null != res.message) {
                  this.$message.error(m(res.message));
                } else if (res.errorMesage != null) {
                  this.$message.error(res.errorMesage);
                } else {
                  this.$message.error("修改失败!");
                }
              } else {
                this.$message.success("修改成功!");
                this.centerDialogVisible = false;
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(_ => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.menu-list {
  min-width: 12vw;
  max-height: 90vh;
  overflow-y: auto;
  div {
    padding: 6px 8px;
    cursor: pointer;
    font-size: 12px;
    &:hover {
      background: #51abd1;
      color: #fff;
    }
  }
}
.letter {
  letter-spacing: -2px;
}
.icon-border {
  display: inline-block;
  border: 1px solid;
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
}
</style>
